package com.chaosyeb.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.chaosyeb.server.pojo.*;
import com.chaosyeb.server.service.*;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * 员工管理
 *
 * @author Chaos
 * @since 2021-12-04
 */
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPoliticsStatusService politicsStatusService;
    @Autowired
    private IJoblevelService jobLevelService;
    @Autowired
    private INationService nationService;
    @Autowired
    private IPositionService positionService;
    @Autowired
    private IDepartmentService departmentService;

    @ApiOperation(value = "获取所有员工（分页+条件）")
    @GetMapping("/")
    public RespPageBean getEmployByPage(@RequestParam(defaultValue = "1") Integer currentPage,
                                        @RequestParam(defaultValue = "10") Integer size,
                                        Employee employee,
                                        LocalDate[] beginDateScope) {
        return employeeService.getEmployByPage(currentPage, size, employee, beginDateScope);
    }

    /**
     * 提前查询出前端页面所需下拉框的内容，包括政治面貌、职称、名族、职位、部门和最大的工号
     */
    @ApiOperation(value = "获取政治面貌")
    @GetMapping("/politicsstatys")
    public List<PoliticsStatus> getAllPoliticsStatus() {
        return politicsStatusService.list();
    }

    @ApiOperation(value = "获取职称")
    @GetMapping("/joblevels")
    public List<Joblevel> getAllJobLevel() {
        return jobLevelService.list();
    }

    @ApiOperation(value = "获取民族")
    @GetMapping("/notions")
    public List<Nation> getAllNation() {
        return nationService.list();
    }

    @ApiOperation(value = "获取所有职位")
    @GetMapping("/positions")
    public List<Position> getAllPosition() {
        return positionService.list();
    }

    @ApiOperation(value = "获取所有部门")
    @GetMapping("/deps")
    public List<Department> getAllDepartment() {
        return departmentService.getAllDepartment();
    }

    @ApiOperation(value = "获取工号")
    @GetMapping("/maxWorkId")
    public RespBean maxWorkId() {
        return employeeService.maxWorkId();
    }

    @ApiOperation(value = "添加员工")
    @PostMapping("/")
    public RespBean addEmp(@RequestBody Employee employee) {
        return employeeService.addEmp(employee);
    }

    @ApiOperation(value = "更新员工")
    @PutMapping("/update")
    public RespBean update(@RequestBody Employee employee) {
        if (employeeService.updateById(employee)) {
            return RespBean.success("更新成功！");
        }
        return RespBean.error("更新失败！");
    }

    @ApiOperation(value = "删除员工")
    @DeleteMapping("/{id}")
    public RespBean delete(@PathVariable("id") Integer id) {
        if (employeeService.removeById(id)) {
            return RespBean.success("删除成功！");
        }
        return RespBean.error("删除失败！");
    }

    @ApiOperation(value = "导出员工数据")
    @GetMapping(value = "/export", produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response) {
        //获取所有员工信息
        List<Employee> list = employeeService.getEmployee(null);
        //导出参数:文件名--sheet页名--导出03版的（兼容性好，速度快）
        ExportParams params = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        //EasyPoi工具类--导出为Workbook
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, list);
        ServletOutputStream out = null;
        try {
            //流的形式
            response.setHeader("content-type", "application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition", "attachment;filename=" +
                    URLEncoder.encode("员工表.xls", "UTF-8"));
            out = response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导入员工数据")
    @PostMapping("/import")
    public RespBean importEmploy(@RequestPart("file") MultipartFile file) {
        //导入参数
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(1);
        //获取nationList
        List<Nation> nationList = nationService.list();
        //获取政治面貌
        List<PoliticsStatus> politicsStatusList = politicsStatusService.list();
        //获取职位
        List<Position> positionList = positionService.list();
        //获取部门
        List<Department> departmentList = departmentService.list();
        //获取职称
        List<Joblevel> jobLevelList = jobLevelService.list();
        try {
            List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            // 因为实体类中只有名字，没有id，导入是需要指定的id下的，用了取巧的方法EqualsAndHashCode方法
            // 对每个元素执行给定的操作，直到所有元素都已被处理或该操作引发异常
            list.forEach(employee -> {
                //获取nation的name对象
                Nation name = new Nation(employee.getNation().getName());
                //拿到name对应的索引下标
                int i = nationList.indexOf(name);
                System.out.println("***i***" + i);
                //根据下标拿到完整的nation对象
                Nation nation = nationList.get(i);
                //拿到了nation的id
                Integer id = nation.getId();
                //民族id
                employee.setNationId(id);
                /*employee.setNationId(nationList.get(nationList.indexOf(
                        new Nation(employee.getNation().getName()))).getId());*/
                //政治面貌id
                employee.setPoliticId(politicsStatusList.get(politicsStatusList.indexOf(
                        new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());
                //部门id
                employee.setDepartmentId(departmentList.get(departmentList.indexOf(
                        new Department(employee.getDepartment().getName()))).getId());
                //职称id
                employee.setJobLevelId(jobLevelList.get(jobLevelList.indexOf(
                        new Joblevel(employee.getJoblevel().getName()))).getId());
                //职位id
                employee.setPosId(positionList.get(positionList.indexOf(
                        new Position(employee.getPosition().getName()))).getId());
            });

            if (employeeService.saveBatch(list)) {
                return RespBean.success("导入成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败！");
    }
}
